package com.sunday.authorization.security.tools.authorization.redis.operation;

import com.sunday.authorization.security.tools.authorization.redis.constants.RedisOAuth2Constants;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 授权操作
 *
 * @author sunday
 * @since 2024/9/24
 */
public class AuthorizationOperation {

    private final StringRedisTemplate stringRedisTemplate;

    public AuthorizationOperation(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 验证token有效性
     *
     * @param principalName
     * @param token
     * @return {@link boolean}
     */
    public boolean validateToken(String principalName, String token) {
        Double score = stringRedisTemplate.opsForZSet().score(RedisOAuth2Constants.getPrincipalName(principalName), token);
        return score != null;
    }

    /**
     * 登出当前登录用户token
     *
     * @param principalName
     * @param token
     * @return {@link boolean}
     */
    public boolean logOutToken(String principalName, String token) {
        Long score = stringRedisTemplate.opsForZSet().remove(RedisOAuth2Constants.getPrincipalName(principalName), token);
        return score > 0;
    }

}
